package com.fjh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.constant.PhoneConstant;
import com.fjh.domain.User;
import com.fjh.mapper.UserMapper;
import com.fjh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean updateById(User user) {
        log.info("更新用户的信息", user.toString());
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        user.setUserLasttime(new Date());
        user.setModifyTime(new Date());
        user.setUserLastip(ip);
        return userMapper.updateById(user) > 0;
    }

    /**
     * 发送短信验证码
     * 1.拿到手机号
     * 2.创建一个验证码
     * 3.把手机号和验证码存入redis
     * 4.组装对象放入mq
     * @param map
     */
    @Override
    public void sendPhoneCode(Map<String, String> map) {
        String phoneNum = map.get("phoneNum");
        //生成验证码
        String code = createCode();
        //把手机号和验证码存入redis
        redisTemplate.opsForValue().set(PhoneConstant.PHONE_PREFIX+phoneNum,code, Duration.ofMinutes(5));

    }

    /**
     * 生成验证码的方法
     * @return
     */
    private String createCode() {
        return "8888";
    }
}

